<template>
  <ProjectBaseInfo />
  <div class="bg-white my-[10px]">
    <BaseHead style="border-bottom: 0">
      项目成员 <el-button @click="handleAdd" :disabled="loading">添加</el-button></BaseHead
    >
    <el-table :data="memberList" class="w-full" border>
      <el-table-column type="index" label="署名" width="60px" />
      <el-table-column label="成员类型">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <CommonSelect
              :isFetch="false"
              :dataList="members"
              v-model="row.memberType"
              valueKey="code"
              :disabled="row.personId == applierId"
              @change="memberTypeChange(row, $event)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-autocomplete
              v-model="row.personName"
              :fetch-suggestions="personSearch(row)"
              clearable
              value-key="name"
              highlight-first-item
              :disabled="row.personId == applierId"
              @select="selectPerson(row, $event)"
              @blur="selectPerosnBlur(row, $event)"
              v-if="row.memberType != 3"
            >
              <template #default="{ item }">
                <span>{{ item.name }}</span>
                <span class="mx-[10px]">{{ item.account }}</span>
                <span>{{ item.unitName }}</span>
              </template>
            </el-autocomplete>
            <el-input clearable v-model="row.personName" v-else />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="工作单位">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <CommonTreeSelect
              :isFetch="false"
              :dataList="allUnitList"
              v-model="row.unitId"
              valueKey="codeColumn"
              labelKey="valueColumn"
              :disabled="row.personId == applierId"
              v-if="row.memberType != 3"
            />
            <el-input clearable v-model="row.unitName" v-else />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="出生年月">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-date-picker
              v-model="row.birthday"
              type="month"
              clearable
              value-format="YYYY-MM-DD"
              :disabled="row.personId == applierId"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="行政职务">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <CommonSelect
              :isFetch="false"
              :dataList="executivePostList"
              v-model="row.executivePost"
              valueKey="code"
              :disabled="row.personId == applierId"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="职称">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <CommonTreeSelect
              :isFetch="false"
              :dataList="applierTitleList"
              v-model="row.titleId"
              check-strictly
              :disabled="row.personId == applierId"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="项目分工">
        <template #default="{ row }">
          <el-input clearable v-model="row.division" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100" align="center">
        <template #default="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleDel($index)"
            v-if="row.personId != applierId"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import ProjectBaseInfo from "./ProjectBaseInfo.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import { sbMember, sbMemberDetail } from "@/api/project/xj/sbxm";
import { getPersonList } from "@/api/project/common";
import { formatDate } from "@/utils/formatTime";
import { ElMessage } from "element-plus";
const operateId = ref(null);
const applierId = ref(""); //申请人id 用于判断项目成员中申请人无法删除
const memberList = ref([]);
const executivePostList = inject("executivePostList"); //行政职务
const applierTitleList = inject("applierTitleList"); //职称
const allUnitList = inject("allUnitList"); //此处需使用所有单位避免科研秘书身份时无法正常显示单位名称
const members = inject("memberList");
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
const loading = ref(false);
//初始化一个项目成员 用于添加
const initMemberItem = () => {
  return {
    memberType: members.value[0].code, //成员类型
    personId: "", //成员id
    personName: "", //成员姓名
    sexId: "", //性别
    birthday: "", //出生年月
    unitId: "", //单位Id
    unitName: "", //单位名称
    executivePost: "", //行政职务
    titleId: "", //职称
    division: "", //项目分工
  };
};
//点击添加按钮
const handleAdd = () => {
  memberList.value.push(Object.assign({}, initMemberItem()));
};
//点击删除按钮删除一行
const handleDel = (index) => {
  memberList.value.splice(index, 1);
};
//获取成员信息详情
const getMemberDetail = async () => {
  const params = {
    id: operateId.value,
  };
  try {
    loading.value = true;
    const res = await sbMemberDetail(params);
    memberList.value = res.data.members;
    applierId.value = res.data.applierId;
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
//编辑
const edit = async (id) => {
  operateId.value = id;
  //获取成员列表
  await getMemberDetail();
  //将出生年月时间戳格式处理成字符串
  memberList.value.forEach((item) => {
    item.birthday = formatDate(item.birthday, "YYYY-MM-DD");
  });
};
//搜索人员列表
const personSearch = (row) => {
  return async (queryString, cb) => {
    if (queryString.trim() == "") {
      return;
    }
    row.personId = "";
    const params = {
      name: queryString,
    };
    try {
      const res = await getPersonList(params);
      cb(res.data);
    } catch (error) {
      console.log(error);
    }
  };
};
//重置成员数据
const resetPerosn = (row) => {
  row.personName = "";
  row.personId = "";
  row.sexId = "";
  row.birthday = "";
  row.unitId = "";
  row.unitName = "";
  row.titleId = "";
};
const selectPerosnBlur = (row) => {
  if (!row.personId) {
    resetPerosn(row);
  }
};
//选择项目成员改变
const selectPerson = (row, val) => {
  //判断所选成员是否已存在
  let existFlag = false;
  memberList.value.forEach((item) => {
    if (item.personId == val.id) {
      existFlag = true;
    }
  });
  if (existFlag) {
    ElMessage({
      message: "所选人员已存在！",
      type: "error",
    });
    resetPerosn(row);
    return;
  }
  row.personId = val.id;
  row.sexId = val.sexId;
  row.birthday = val.birthday;
  row.unitId = val.unitId;
  row.unitName = val.unitName;
  row.titleId = val.titleId;
};
//选择的成员类型改变
const memberTypeChange = (row, val) => {
  //选择校外时或者从校外选择校内或学生时 清空成员信息
  if (val == 3 || (val != 3 && row.personId == "")) {
    resetPerosn(row);
  }
};
const emit = defineEmits(["save-success", "save-ok"]);
//保存
const save = async (submitType) => {
  try {
    //设置orderId字段的值
    let fieldFlag = true;
    memberList.value.forEach((item, index) => {
      item.orderId = index + 1;
      if (index != 0) {
        if (
          !item.personName ||
          !item.birthday ||
          !item.unitName ||
          !item.executivePost ||
          !item.titleId
        ) {
          fieldFlag = false;
        }
      }
    });
    //校验必填字段是否全部填写
    if (!fieldFlag) {
      ElMessage({
        message: "请检查各项必填字段是否全部填写！",
        type: "error",
      });
      return;
    }
    let params = {
      id: operateId.value,
      submitType,
      isAuditor: isAuditor.value,
      taskId: taskId.value,
      checkstatus: checkStatus.value,
      members: memberList.value,
    };
    const res = await sbMember(params);
    if (res.code === 200) {
      emit("save-success");
    }
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ edit, save });
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
